package com.znsd.stu.controllor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.znsd.entitys.Leave;
import com.znsd.entitys.RoleInfo;
import com.znsd.entitys.ShiftDuty;
import com.znsd.entitys.Users;
import com.znsd.stu.service.LeaveService;
import com.znsd.stu.service.RoleService;
import com.znsd.stu.service.UserService;
import com.znsd.stu.service.ZhuanBanService;
import com.znsd.utils.CodeRes;

/**
 * 
 * @ClassName: UserControllor
 * @Description: TODO(用户操作)
 * @author Liuyl
 * @date 2019年8月20日
 *
 */
@Controller
public class UserControllor {
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private LeaveService leaveService;
	@Autowired
	private ZhuanBanService zhuanBanService;

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String checkUsername(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Users lo = (Users) session.getAttribute("user");
		if (lo != null) {
			return "redirect:index";
		}
		String scode = (String) request.getSession().getAttribute("scode");
		String code = request.getParameter("code");
		if (scode.equalsIgnoreCase(code)) {
			String username = request.getParameter("inputEmail");
			String password = request.getParameter("inputPassword");
//			Users user = userService.checkUsername(username, password);
//			if (user != null) {
//				session.setAttribute("user", user);
//				return "redirect:index";
//			} else {
//				session.setAttribute("msg", "用户名或密码错误");
//				return "admin/login";
//			}
			// 获取当前的Subject
			Subject currentUser = SecurityUtils.getSubject();
			// 测试当前用户是否已经被认证，即是否已经登录。
			if (!currentUser.isAuthenticated()) {
				// 把用户名和密码封装为UsernamePasswordToken对象
				UsernamePasswordToken token = new UsernamePasswordToken(username, password);
				// 记住密码
				token.setRememberMe(true);
				try {
					System.out.println("用户名密码验证通过，执行登录");
					// 执行登录
					currentUser.login(token); // 实际上调用Realm中的doGetAuthenticationInfo方法
					return "redirect:index";
				} catch (UnknownAccountException uae) { // 用户名不存在
					session.removeAttribute("user");
					System.err.println("用户不存在! " + token.getPrincipal());
				} catch (IncorrectCredentialsException ice) { // 密码错误
					session.removeAttribute("user");
					System.err.println("用户密码错误! ");
				} catch (LockedAccountException lae) { // 账户锁定
					session.removeAttribute("user");
					System.err.println("账户锁定");
				} catch (AuthenticationException ae) {
					session.removeAttribute("user");
					System.err.println("其他异常");
				}
			}
			return "admin/login";
		} else {
			session.setAttribute("msg", "验证码错误");
			return "admin/login";
		}
	}

	@RequestMapping(value = "index")
	public String index() {
		return "admin/index";
	}

	@RequestMapping(value = "head")
	public String indexHead() {
		return "admin/head";
	}

	@RequestMapping(value = "left")
	public String indexLeft() {
		return "admin/left";
	}

	@RequestMapping(value = "nav")
	public String indexNav() {
		return "admin/nav";
	}

	@RequestMapping(value = "home")
	public String indexHome() {
		return "admin/home";
	}

	@RequestMapping(value = "login")
	public String login() {
		return "admin/login";
	}

	// 注册开始（跳转注册页面）
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register() {
		return "admin/register";
	}

	// ajax验证手机号是否被注册
	@ResponseBody
	@RequestMapping(value = "checkphone", method = RequestMethod.POST)
	public String checkPhone(String phone, HttpServletResponse r) {
//		System.out.println(phone);
		Users user = userService.checkUserPhone(phone);
		if (user != null) {
			return "true";
		}
		return "";
	}

	// ajax获取验证码
	@ResponseBody
	@RequestMapping(value = "gaincode", method = RequestMethod.POST)
	public String gaincode(String phone, HttpServletRequest request) {
		System.out.println(phone);
		String code = (int) (Math.random() * 10000) + "";
		if (code.length() != 4) {
			int a = 4 - code.length();
			for (int i = 0; i < a; i++) {
				code = "0" + code;
			}
		}
		//CodeRes.getRequest2(phone, code + "");
		System.out.println(code);
		HttpSession session = request.getSession();
		session.setAttribute(phone, code);
		return code + "";
	}

	@ResponseBody
	@RequestMapping(value = "checkcode", method = RequestMethod.POST)
	public Boolean checkCode(String phone, String code, HttpServletRequest request) {
		System.out.println(phone);
		System.out.println(code);

		HttpSession session = request.getSession();
		String c = (String) session.getAttribute(phone);
		if (code.equals(c)) {
			return true;
		}
		return false;
	}

	// 验证用户名是否唯一
	@ResponseBody
	@RequestMapping(value = "checkuser", method = RequestMethod.POST)
	public String checkUser(String username) {
		System.out.println(username);
		Users user = userService.checkUsername(username, null);
		if (user != null) {
			return "true";
		}
		return "";
	}

	// 注册
	@RequestMapping(value = "registerpost", method = RequestMethod.POST)
	public String registerpost(Users user) {
		System.out.println(user);
		// 生成加密的盐值
		ByteSource salt = ByteSource.Util.bytes(user.getUser_username());
		// 进行MD5加密
		SimpleHash sh = new SimpleHash("MD5", user.getUser_password(), salt, 10);
		user.setUser_password(sh.toString());
		userService.addUser(user);
		return "admin/login";
	}

	// 跳转信息录入界面
	@RequestMapping(value = "entering", method = RequestMethod.GET)
	public String entering() {
		return "admin/entering";
	}

	// 信息录入
	@RequestMapping(value = "entering", method = RequestMethod.POST)
	public String enteringPost(Users user) {
		Integer count = userService.updateUser(user);
		if (count == null) {
			return "admin/entering";
		}
		return "redirect:home";
	}

	// 跳转查看个人信息界面
	@RequestMapping(value = "lockentering", method = RequestMethod.GET)
	public String lockentering() {
		return "admin/lock_entering";
	}

	// 跳转查看角色分配界面
	@RequestMapping(value = "roleFenpei", method = RequestMethod.GET)
	public String roleFenpei() {
		return "admin/role_fp";
	}

	// 获取用户数据
	@ResponseBody
	@RequestMapping(value = "userRoleList", method = RequestMethod.GET)
	public Map<String, Object> userRoleList(Integer page, Integer limit) {
		Integer pageIndex = (page - 1) * limit;
		List<Users> userAll = userService.queryLimitUser(pageIndex, limit);
		for (Users users : userAll) {
			System.out.println("...................." + users.getRole());
		}
		Integer count = userService.queryUserCount();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "成功");
		map.put("count", count);
		map.put("data", userAll);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "getRoleAll", method = RequestMethod.GET)
	public Map<String, Object> getRoleAll() {
		List<RoleInfo> roleAll = roleService.getRoleAll();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "成功");
		map.put("data", roleAll);
		return map;
	}

	// 角色分配
	@RequestMapping(value = "userRoleEdit", method = RequestMethod.POST)
	public String userRoleEdit(Users user, Integer quanxian) {
		Integer count = userService.updateuserRole(user, quanxian);
		if (count == null) {
			return "admin/role_fp";
		}
		return "redirect:home";
	}

	// 申请转班页面跳转
	@RequestMapping(value = "changeclazz", method = RequestMethod.GET)
	public String changeclazz(Users user, Integer quanxian) {
		return "admin/changeclazz";
	}

	// 申请转班处理
	@ResponseBody
	@RequestMapping(value = "changeclazz", method = RequestMethod.POST)
	public String changeclazzPost(Integer likeClazz, Integer clazzId, Integer stuId) {
		System.out.println("像转入班级id:" + likeClazz + "   旧的班级id:" + clazzId + "   学生ID：" + stuId);
		Integer zhuanbanId = zhuanBanService.addZhuanBan(likeClazz, clazzId, stuId);
		if (zhuanbanId == null) {
			return "0";
		}
		return "1";
	}

	// 转班详情跳转
	@RequestMapping(value = "changeclazzdetail", method = RequestMethod.GET)
	public String changeclazzdetail() {
		return "admin/changeclazzdetail";
	}

	// 获取个人转班的数据
	@ResponseBody
	@RequestMapping(value = "getchangeclazz", method = RequestMethod.GET)
	public Map<String, Object> getChangeclazz(HttpServletRequest request, Integer page, Integer limit) {
		Users user = (Users) request.getSession().getAttribute("user");
		Integer pageIndex = (page - 1) * limit;
		List<ShiftDuty> zhuanUserAll = zhuanBanService.queryLimitUserZhuan(user.getUser_id(), pageIndex, limit);
		Integer count = zhuanBanService.queryLimitUserZhuanCount(user.getUser_id());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "成功");
		map.put("count", count);
		map.put("data", zhuanUserAll);
		return map;
	}
	
	// 要取消的转班ID
	@ResponseBody
	@RequestMapping(value = "editChangeclazz", method = RequestMethod.POST)
	public Map<String, Object> editChangeclazz(Integer id) {
		System.out.println("要取消转班的ID："+id);
		Integer resule = zhuanBanService.updateZhuanBan(id);
		Map<String, Object> map = new HashMap<String, Object>();
		if (resule == 0) {
			map.put("code", 1);
		} else {
			map.put("code", 0);
		}
		return map;
	}

	// 请假跳转
	@RequestMapping(value = "leave", method = RequestMethod.GET)
	public String userLeave(Users user, Integer quanxian) {
		return "admin/leave";
	}

	// 请假申请
	@RequestMapping(value = "leave", method = RequestMethod.POST)
	public String userLeavePost(Leave leave) {
		Integer resule = leaveService.addLeave(leave);
		if (resule == null) {
			return "admin/leave";
		}
		return "redirect:home";
	}

	// 请假详情跳转
	@RequestMapping(value = "leavedetail", method = RequestMethod.GET)
	public String leavedetail() {
		return "admin/leavedetail";
	}

	// 获取个人请假的数据
	@ResponseBody
	@RequestMapping(value = "getleavedetail", method = RequestMethod.GET)
	public Map<String, Object> getLeavedetail(HttpServletRequest request, Integer page, Integer limit) {
		Users user = (Users) request.getSession().getAttribute("user");
		Integer pageIndex = (page - 1) * limit;
		List<Leave> leaveUserAll = leaveService.queryLimitUserLeave(user.getUser_id(), pageIndex, limit);
		Integer count = leaveService.queryLimitUserLeaveCount(user.getUser_id());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "成功");
		map.put("count", count);
		map.put("data", leaveUserAll);
		return map;
	}

	// 取消请假
	@ResponseBody
	@RequestMapping(value = "editleavedetail", method = RequestMethod.POST)
	public Map<String, Object> editleavedetail(Integer id) {
		Integer resule = leaveService.updateQuxiao(id);
		Map<String, Object> map = new HashMap<String, Object>();
		if (resule == 0) {
			map.put("code", 1);
		} else {
			map.put("code", 0);
		}
		return map;
	}
}
